<template>
	<div class="login-wrap" :style="backgroundDiv">
		<div class="ms-login">
			<div class="ms-title">谁是卧底 - 玩家注册</div>
				<van-form :show-error="false" :model="params" class="ms-content">
					<van-field v-model="params.nickname"
								label="游戏昵称"
								clearable
								placeholder="请输入您的游戏昵称"
								:rules="[{ validator: validateNickname , required: true , message:'仅支持中文或者中文，最少两字'}]"/>
					<van-field v-model="params.telphone"
								label="手机号"
								clearable
								placeholder="请输入您的手机号"
								:rules="[{ validator: validatePhone , required: true , message:'请输入正确的电话号码'}]"/>
					<van-field v-model="params.phone_code"
							   center
							   clearable
							   label="短信验证码"
							   placeholder="请输入短信验证码"
							   :rules="[{ validator: validatePhoneCode , required: true ,message:'请输入六位数字验证码' }]">
						<template #button>
							<van-button size="small" type="primary" v-if="sendCodeButton" @click="send_tel_code">{{button_content}}</van-button>
							<van-button size="small" type="default" v-else>{{button_content}}</van-button>
						</template>
					</van-field>
					<van-field v-model="params.password"
								type="password"
								label="密码"
								clearable
								placeholder="请输入您的游戏密码"
								:rules="[{ validator: isPassword , required: true , message:'请输入您的游戏密码（6-18位）'}]"/>
					<div style="margin: 16px;" class="login-btn">
						<van-button round block type="info" native-type="submit" @click="onSubmit">提交注册信息</van-button>
					</div>
				</van-form>
				<div class="login-tips">
					<van-row type="flex" justify="end">
						<van-col span="6" @click="navTo('/user_login')">返回登陆</van-col>
					</van-row>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			backgroundDiv: {
				backgroundImage:'url(' + require('../../../public/images/background.jpg') + ')',
				height:'100vh',
				backgroundRepeat:'no-repeat',
				backgroundSize:'100% 100%'
			},
			button_content:'发送验证码',
			sendCodeButton:true,
			params:{
				nickname: '颜旭升',
				password: 'jiannei0507',
				telphone:'17611325509',
				phone_code:'123456',
			},
		};
	},
	mounted(){
		//开始背景图片自适应
		this.setImgSize();
		//屏幕尺寸改变的监听方法
		window.onresize = () => {
			this.setImgSize(); 
		}
	},
	methods: {
		validateNickname(val){
			return /[\u4e00-\u9fa5a-zA-Z]{2}/.test(val);
		},
		isPassword(val){
			return /[_a-zA-Z0-9]{6,18}/.test(val);
		},
		validatePhone(val){
			return /[1][3,4,5,7,8][0-9]{9}/.test(val);
		},
		validatePhoneCode(val){
			return /\d{6}/.test(val);
		},
		setImgSize(){
			let height = document.body.clientHeight+"px"; //获取可见区域的高
			let width = document.body.clientWidth+"px";//获取可见区域的宽
			this.$set(this.backgroundDiv,'backgroundSize',width+""+height);
		},
		send_tel_code (){
			// 校验手机号
			if (!this.validatePhone(this.params.telphone)) {
				this.$toast.fail('请输入正确的手机号码'); return false;
			}
			
			let _this = this;
			// 请求后台发送验证码至手机
			this.$post('/game/player/sendtelphonecode', {'telphone':this.params.telphone}).then(res => {
				let count_time = 60;
				let this_count = 60;
				let timer = '';
				timer = window.setInterval(() => {
					if (this_count > 0 && this_count <= count_time){
						// 倒计时时不可点击 - 计时秒数 - 更新按钮的文字内容
						_this.sendCodeButton = false;
						this_count--;
						_this.button_content = this_count+'s后重新获取';
					} else {
						// 倒计时完，可点击 - 更新按钮文字内容 - 清空定时器
						_this.sendCodeButton = true;
						_this.button_content = '获取短信验证码';
						
						clearInterval(timer);
						timer = null;
					}
				}, 1000);
				
				if (res.code == 200) {
					this.$toast({ message: res.msg, position: 'bottom',duration: 10000 });
				} else if (res.code == 201) {
					this.$dialog.alert({ message:res.msg, theme: 'round-button' }).then(() => { 
						this.$router.push('/user_login');
					});
				} else {
					this.$toast({ message: res.msg, position: 'bottom',duration: 2000 });
				}
			}).catch((e) => {
				console.log(e);
				this.$notify({ type: 'danger', message: '连接服务器失败' });
			});
		},
		onSubmit() {
			let toast = this.$toast.loading({ duration: 0, forbidClick: true, message: '请稍后...' });
			this.$post('/game/player/register', this.params).then(res => {
				toast.clear();
				
				if (res.code == 200) {
					let _this = this;
					
					this.$dialog.confirm({ title: '提示', message: res.msg, theme: 'round-button'}).then(() => {
						_this.$notify({ type: 'success', message: '登录成功，欢迎回来' });
						
						_this.$setCookie('user_token', res.data._token);
						this.$delete(res.data,'_token');
						_this.$setCookie('user_info', JSON.stringify(res.data));
						
						_this.$router.push('/game_hall');
					});
				} else if (res.code == 201) {
					this.$dialog.alert({ message:res.msg, theme: 'round-button' }).then(() => { 
						this.$router.push('/user_login') 
					});
				} else {
					this.$toast({ message: res.msg, position: 'bottom',duration: 2000 });
				}
			}).catch((e) => {
				toast.clear();
				console.log(e);
				this.$notify({ type: 'danger', message: '连接服务器失败' });
			});
		},
		navTo(path) {
			this.$router.push(path);
		},
		failed(){
			this.$notify({ type: 'danger', message: '连接服务器失败' });
		}
	}
};
</script>
<style scoped>
.login-wrap {
    position: relative;
    width: 100%;
    height: 100%;
}
.ms-title {
    width: 100%;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    color: black;
    border-bottom: 1px solid #ddd;
}
.ms-login {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 350px;
    margin: -190px 0 0 -175px;
    border-radius: 5px;
    background: rgba(255, 255, 255, 0.3);
    overflow: hidden;
}
.login-btn {
    text-align: center;
}
.login-tips {
    line-height: 30px;
}
</style>